package algotithm.leetcode.slidingwindow.test159;

import java.util.Collections;
import java.util.HashMap;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/16-11:38
 * @URL https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters/
 * @Title 159. 至多包含两个不同字符的最长子串
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "ccaabbb";
        int length = solution.lengthOfLongestSubstringTwoDistinct(s);
        System.out.println(length);
    }

    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int n = s.length();
        if (n < 3) {
            return n;
        }
        HashMap<Character,Integer> map = new HashMap<>();
        int l = 0,r = 0;
        int max = 2;
        while (r < n) {
            if (map.size() < 3) {
                map.put(s.charAt(r),r++);
            }
            if (map.size() == 3) {
                int  index = Collections.min(map.values());
                map.remove(s.charAt(index));
                l = index + 1;
            }
            max = Math.max(max,r - l);
        }
        return max;
    }
}